import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  url = 'http://127.0.0.1:8080/lx/';
  loginForm: FormGroup;
  imgUrl: string;
  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private router: Router,
  ) { }
  ngOnInit() {
    this.loginForm = this.fb.group({
      account: ['', Validators.required],
      pwd: ['', Validators.required],
      code: ['', Validators.required],
    });
    localStorage.setItem('url', this.url);
    this.getCode();
  }
  getCode() {
    this.imgUrl = localStorage.getItem('url') + 'getVerify?' + new Date().getMilliseconds();
  }
  submit(value) {
    this.http.post(localStorage.getItem('url') + 'login', {
      account: value.account,
      pwd: value.pwd,
      code: value.code
    }).subscribe( v => {
      if (v['code'] === 0) {
        localStorage.setItem('userInfo', JSON.stringify(v['data']));
        // alert('登录成功!');
        this.router.navigate(['proUserList']);
      } else {
        alert('登录失败!');
      }
    });
  }

  getFormControl(name) {
    return this.loginForm.controls[name];
  }
}
